 package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

 @Slf4j
 @Component
 public class OrderReceiver {

     @Autowired
     private OrderInfoService orderInfoService;

     /**
      * 订单取消成功
      * @param orderNo
      * @param message
      * @param channel
      */
     @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
     public void cancelOrder(String orderNo, Message message, Channel channel) {
         log.info("订单取消成功：{}", orderNo);
         try {
             //  判断
             if (!StringUtils.isEmpty(orderNo)){
                 //  取消订单;
                 orderInfoService.cancelOrder(orderNo);
             }
         } catch (Exception e) {
             //  重试+落库
             log.error(e.getMessage(),e);
         }
         //  手动签收;
         try {
             channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
         } catch (IOException e) {
             throw new RuntimeException(e);
         }
     }

     /**
      * 订单支付成功
      * @param orderNo
      * @param message
      * @param channel
      */
     @RabbitListener(bindings = @QueueBinding(
             value = @Queue(value = MqConst.QUEUE_ORDER_PAY_SUCCESS, durable = "true",autoDelete = "false"),
             exchange = @Exchange(value = MqConst.EXCHANGE_ORDER),
             key = MqConst.ROUTING_ORDER_PAY_SUCCESS
     ))
     public void orderPaySuccess(String orderNo, Message message, Channel channel) {
         //  获取订单编号
         if (!StringUtils.isEmpty(orderNo)){
             //  修改订单状态;
             orderInfoService.orderPaySuccess(orderNo);
         }
         //  手动确认;
         try {
             channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
         } catch (IOException e) {
             log.error(e.getMessage(),e);
         }
     }
 }

